package com.myWeb.util;


import javax.servlet.ServletContext;
import java.sql.*;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;

public class JdbcUtil {

    //资源绑定
    static ResourceBundle bundle = ResourceBundle.getBundle("com/myWeb/util/jdbc2");
    static String driver = bundle.getString("driver");
    static String url  = bundle.getString("url");
    static String user = bundle.getString("user");
    static String password = bundle.getString("password");
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    //注册驱动
    static{
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接对象
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    public Connection getConnection(javax.servlet.http.HttpServletRequest request) throws SQLException {

        ServletContext application = request.getServletContext();
        Map map = (Map)application.getAttribute("key1");
        Iterator it = map.keySet().iterator();
        while(it.hasNext()){
            conn = (Connection)it.next();
           boolean flag = (boolean)map.get(conn);
           if(flag){
               map.put(conn,false);
               break;
           }
        }
        return conn;

    }

    public PreparedStatement createStatement(String sql, javax.servlet.http.HttpServletRequest request)
            throws SQLException{

        return getConnection(request).prepareStatement(sql);

    }

    public void close(ResultSet rs, PreparedStatement ps, Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void close(javax.servlet.http.HttpServletRequest request){

        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        ServletContext application = request.getServletContext();
        Map map = (Map)application.getAttribute("key1");
        map.put(conn,true);
    }

}


